package com.jzt.jk.util;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.jzt.jk.request.OpenApiRequest;
import com.jzt.jk.response.BaseResponse;
import java.util.Map;

/**
 * @Author xuyl
 * @Date 2023/1/31 16:59
 * @Version 1.5
 */

public class OpenApiUtil {


    /**
     * test = https://open-api.test.jk.com/platform,
     * prod = https://open.jk.com/platform
     */
    private static final String DOMAIN = "https://open-api.test.jk.com/platform";

    private static final String APP_KEY = "f6a35408c1e042f9baacc43a517461f2";
    private static final String APP_SECRET = "df2cf26055984995b9366f2ebf62a414";

    public static BaseResponse post(OpenApiRequest request) throws Exception {
        HttpRequest postRequest = HttpUtil.createPost(DOMAIN + request.path());
        // 公共请求头参数
        Map<String, String> metaDataMap = SignatureUtil.buildMetaDataMap(request.action(), APP_KEY);
        String signature = SignatureUtil.generateSignature(APP_SECRET, metaDataMap, request);
        System.out.println("signature= " + signature);
        metaDataMap.put(SignatureUtil.HEADER_SIGNATURE, signature);
        postRequest.addHeaders(metaDataMap);
        postRequest.body(JSON.toJSONString(request));
        String resultJson = postRequest.execute().body();
        return JSONUtil.toBean(resultJson, BaseResponse.class);
    }

}
